package com.example.weibo_suhuanzhen.homeRecycle;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.example.weibo_suhuanzhen.R;
import com.example.weibo_suhuanzhen.UserSession;
import com.example.weibo_suhuanzhen.activities.DetailActivity;
import com.example.weibo_suhuanzhen.activities.LoginActivity;
import com.example.weibo_suhuanzhen.adapters.ImageGridAdapter;
import com.example.weibo_suhuanzhen.adapters.MyAdapter;
import com.example.weibo_suhuanzhen.bean.BaseBean;
import com.example.weibo_suhuanzhen.bean.WeiboInfo;
import com.example.weibo_suhuanzhen.homeRecycle.LikeCallback;
import com.example.weibo_suhuanzhen.retrofit.RetrofitManager;
import com.example.weibo_suhuanzhen.retrofit.ShzApi;
import com.example.weibo_suhuanzhen.sharedPreferences.SharedPreferencesManager;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ImageViewHolder extends RecyclerView.ViewHolder {
    final String TAG="shz_ImageViewHolder";
    private MyAdapter myAdapter;
    private Context context;
    private ImageView singleImageView;
    private RecyclerView recyclerView;
    private TextView username;
    private ImageView avatar;
    private TextView title;
    private TextView like;
    ImageView im_like;//点赞图标
    private boolean isLiked;
    private ImageView delete;
    private TextView comment;
    private SharedPreferencesManager preferences;


    public ImageViewHolder(@NonNull View itemView, Context context, MyAdapter myAdapter) {
        super(itemView);
        this.context = context;
        this.myAdapter = myAdapter;
        this.preferences = SharedPreferencesManager.getInstance(context.getApplicationContext());
        singleImageView = itemView.findViewById(R.id.single_image_view);
        recyclerView = itemView.findViewById(R.id.image_recycler_view);
        username = itemView.findViewById(R.id.username_in_image);
        avatar = itemView.findViewById(R.id.avatar_in_image);
        title = itemView.findViewById(R.id.title_in_image);
        like = itemView.findViewById(R.id.tv_like_inImage);
        im_like = itemView.findViewById(R.id.im_like);
        delete = itemView.findViewById(R.id.delete_in_image);
        comment = itemView.findViewById(R.id.tv_comment);
    }

    public void bind(WeiboInfo item, MyAdapter.ItemActionListener itemActionListener,int position) {
        username.setText(item.getUsername());
        title.setText(item.getTitle());
        like.setText(String.valueOf(item.getLikeCount()));
        isLiked=item.isLikeFlag();
        if (isLiked){
            like.setTextColor(Color.parseColor("#e65231"));
            im_like.setImageResource(R.drawable.heart_red);
        }else {
            like.setTextColor(Color.parseColor("#000000"));
            im_like.setImageResource(R.drawable.heart);
        }
        //评论点击
        comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) {
                    Toast.makeText(context,"点击第"+(position+1)+"条数据评论按钮",Toast.LENGTH_SHORT).show();
                }
            }
        });
        //点赞逻辑

        like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!UserSession.getInstance().isLoggedIn()){
                    Intent intent = new Intent(context, LoginActivity.class);
                    context.startActivity(intent);
                }
                else if (!isLiked){
                    like.setText(String.valueOf(item.getLikeCount() + 1));
                    item.setLikeCount(item.getLikeCount() + 1);
                    like.setTextColor(Color.parseColor("#e65231"));
                    im_like.setImageResource(R.drawable.heart_red);
                    performLike(im_like);
                    isLiked = true;
                    sendLike(item.getId(), new LikeCallback() {
                        @Override
                        public void onSuccess() {

                        }
                        @Override
                        public void onFailure() {
                            Toast.makeText(context, "点赞失败", Toast.LENGTH_SHORT).show();
                            like.setText(String.valueOf(item.getLikeCount()-1));
                            item.setLikeCount(item.getLikeCount()-1);
                            like.setTextColor(Color.BLACK);
                            im_like.setImageResource(R.drawable.heart);
                            performCancelLike(im_like);
                            isLiked=false;
                        }
                    });
                }else {
                    like.setText(String.valueOf(item.getLikeCount()-1));
                    item.setLikeCount(item.getLikeCount()-1);
                    like.setTextColor(Color.BLACK);
                    im_like.setImageResource(R.drawable.heart);
                    performCancelLike(im_like);
                    isLiked=false;
                    sendCancelLike(item.getId(), new LikeCallback() {
                        @Override
                        public void onSuccess() {

                        }
                        @Override
                        public void onFailure() {
                            Toast.makeText(context,"取消点赞失败，请检查网络", Toast.LENGTH_SHORT).show();
                            like.setText(String.valueOf(item.getLikeCount() + 1));
                            item.setLikeCount(item.getLikeCount() + 1);
                            like.setTextColor(Color.parseColor("#e65231"));
                            im_like.setImageResource(R.drawable.heart_red);
                            performLike(im_like);
                            isLiked = true;
                        }
                    });
                }
            }
        });

        Glide.with(context)
                .load(item.getAvatar())
                .transform(new CircleCrop())
                .into(avatar);

        List<String> imageUrls = item.getImages();
        if (imageUrls.size() == 1) {
            recyclerView.setVisibility(View.GONE);
            singleImageView.setVisibility(View.VISIBLE);
//                Glide.with(context).load(imageUrls.get(0)).into(singleImageView);

            //加载单个图片
            Glide.with(context)
                    .load(imageUrls.get(0))
                    .addListener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            // 获取图片的宽高信息
                            int width = resource.getIntrinsicWidth();
                            int height = resource.getIntrinsicHeight();

                            // 计算宽高比
                            float aspectRatio = (float) width / height;

                            // 根据宽高比设置样式
                            if (aspectRatio > 1) {
                                // 显示横图样式
                                singleImageView.setScaleType(ImageView.ScaleType.FIT_START);
                            } else {
                                // 显示竖图样式
                                singleImageView.setScaleType(ImageView.ScaleType.FIT_START);
                            }

                            return false;
                        }
                    })
                    .into(singleImageView);

            //对单个图片设置点击监听器
            singleImageView.setOnClickListener(v -> {
                Intent intent = new Intent(context, DetailActivity.class);
                intent.putExtra("username", item.getUsername());
                intent.putExtra("avatar", item.getAvatar());
                intent.putStringArrayListExtra("images", new ArrayList<>(imageUrls));
                intent.putExtra("position",1);
                context.startActivity(intent);
            });

//                Picasso.get().load(imageUrls.get(0)).into(singleImageView);
        } else {
            singleImageView.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
            recyclerView.setLayoutManager(new GridLayoutManager(itemView.getContext(), 3));
            ImageGridAdapter imageAdapter = new ImageGridAdapter(itemView.getContext(), imageUrls,item);
            recyclerView.setAdapter(imageAdapter);
        }
        //删除视图
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) {
                    myAdapter.removeItem(position);
                }
            }
        });

        //跳转
        singleImageView.setOnClickListener(v -> {
            Intent intent = new Intent(context, DetailActivity.class);
            intent.putExtra("username", item.getUsername());
            intent.putExtra("avatar", item.getAvatar());
            intent.putStringArrayListExtra("images", new ArrayList<>(imageUrls));
            context.startActivity(intent);
        });


    }
    private void performLike(View view) {
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1f, 1.2f, 1f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1f, 1.2f, 1f);
        ObjectAnimator rotationY = ObjectAnimator.ofFloat(view, "rotationY", 0f, 360f);

        scaleX.setInterpolator(new AccelerateDecelerateInterpolator());
        scaleY.setInterpolator(new AccelerateDecelerateInterpolator());
        rotationY.setInterpolator(new AccelerateDecelerateInterpolator());

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(scaleX, scaleY, rotationY);
        animatorSet.setDuration(1000);
        animatorSet.start();
    }

    private void performCancelLike(View view) {
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1f, 0.8f, 1f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1f, 0.8f, 1f);

        scaleX.setInterpolator(new AccelerateDecelerateInterpolator());
        scaleY.setInterpolator(new AccelerateDecelerateInterpolator());

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(scaleX, scaleY);
        animatorSet.setDuration(1000);
        animatorSet.start();
    }

    private void sendLike(Long id , LikeCallback callback){
        ShzApi shzApi = RetrofitManager.getInstance().createApi();
        ShzApi.LikeEventRequest likeEventRequest = new ShzApi.LikeEventRequest(id);
        Call<BaseBean<Boolean>> call = shzApi.sendLike("Bearer " + preferences.getData("token",""), likeEventRequest);
        call.enqueue(new Callback<BaseBean<Boolean>>() {
            @Override
            public void onResponse(Call<BaseBean<Boolean>> call, Response<BaseBean<Boolean>> response) {
                if (response.isSuccessful()) {
                    BaseBean<Boolean> body = response.body();
                    if (body != null && body.data!=null && body.data && body.code==200) {
                        Log.d(TAG, "点赞成功");
                        callback.onSuccess();
                    } else {
                        Log.d(TAG, "点赞失败：" + body != null ? body.msg : "unknown error");
                        callback.onFailure();
                    }
                } else {
                    Log.d(TAG, "响应失败：" + response.message());
                    callback.onFailure();
                }
            }
            @Override
            public void onFailure(Call<BaseBean<Boolean>> call, Throwable t) {
                Log.d(TAG, "请求失败：" + t.getMessage());
                callback.onFailure();
            }
        });
    }
    private void sendCancelLike(Long id,LikeCallback callback){
        ShzApi shzApi = RetrofitManager.getInstance().createApi();
        ShzApi.LikeEventRequest likeEventRequest = new ShzApi.LikeEventRequest(id);
        Call<BaseBean<Boolean>> call = shzApi.sendCancelLike("Bearer " + preferences.getData("token",""), likeEventRequest);
        call.enqueue(new Callback<BaseBean<Boolean>>() {
            @Override
            public void onResponse(Call<BaseBean<Boolean>> call, Response<BaseBean<Boolean>> response) {
                if (response.isSuccessful()) {
                    BaseBean<Boolean> body = response.body();
                    if (body != null && body.data!=null && body.data && body.code==200) {
                        Log.d(TAG, "取消点赞成功");
                        callback.onSuccess();
                    } else {
                        Log.d(TAG, "取消点赞失败：" + body != null ? body.msg : "unknown error");
                        callback.onFailure();
                    }
                } else {
                    Log.d(TAG, "响应失败：" + response.message());
                    callback.onFailure();
                }
            }
            @Override
            public void onFailure(Call<BaseBean<Boolean>> call, Throwable t) {
                Log.d(TAG, "请求失败：" + t.getMessage());
                callback.onFailure();
            }
        });
    }
}